package com.chart.common.utils;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import java.security.Security;
import java.util.Properties;

public final class MailUntils {
	private MailUntils() {}
	
	public static Session createSession() {
		Session session = null;

		try {
			//设置SSL连接、邮件环境
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
			Properties props = System.getProperties();
			//协议
			props.setProperty("mail.transport.protocol", "smtp");

			props.setProperty("mail.smtp.host", "smtp.qiye.aliyun.com");//smtp服务器地址
//            props.setProperty("mail.smtp.port", "25");//非加密端口
			// 使用ssl加密方式，进行如下配置：
			props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
			props.setProperty("mail.smtp.socketFactory.fallback", "false");
			props.setProperty("mail.smtp.socketFactory.port", "465");

			props.setProperty("mail.smtp.auth", "true");//表示SMTP发送邮件，需要进行身份验证

			props.setProperty("mail.smtp.from", "qiye@chipshare.cn");//mailfrom 参数
			props.setProperty("mail.user","qiye@chipshare.cn");//发件人的账号
			props.setProperty("mail.password","EjFTG1Wy2Yu9kp7K");// 发件人的账号的密码，如果开启三方客户端安全密码请使用新生产的密码
			//建立邮件会话
			session = Session.getDefaultInstance(props, new Authenticator() {
				//身份认证
				protected PasswordAuthentication getPasswordAuthentication() {
					//发件人的账号、密码
					String userName = props.getProperty("mail.user");
					String password = props.getProperty("mail.password");
					return new PasswordAuthentication(userName, password);
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}

		//  控制台打印调试信息
		session.setDebug(true);
		return session;
 
	}
}